package pw.hais.bankcalling.app;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android_serialport_api.ChuanKouUtils;
import android_serialport_api.DevicesInfo;
import de.greenrobot.event.EventBus;
import pw.hais.app.AppApplication;
import pw.hais.bankcalling.dao.AudioDao;
import pw.hais.bankcalling.entity.EventT;
import pw.hais.bankcalling.entity.Machine;
import pw.hais.bankcalling.entity.greendao.DaoMaster;
import pw.hais.bankcalling.entity.greendao.DaoSession;
import pw.hais.utils.SPUtil;

/**
 * Application
 * Created  on 2016/7/22/022.
 */
public class HaisApp extends AppApplication {
    public static Machine machine;                      //机器信息

    public static ChuanKouUtils callUtil;               //串口信号
    public static ChuanKouUtils printUtil;              //打印机
    public static AudioDao audioUtil;                       //百度语音
    public static DaoSession daoSession;                //GreenDao


    @Override
    public void onCreate() {
        super.onCreate();

        initGreenDao();
        machine = SPUtil.getObject(V.SP_MACHINE_MODEL_KEY, Machine.class, null);

        callUtil = new ChuanKouUtils(new DevicesInfo("ttyS2", "/dev/ttyS2"), 19200) {
            @Override
            protected void onDataReceived(byte[] buffer, int size) {
                Log.i("ChuanKouInfo", "收到串口信息：" + ChuanKouUtils.showByte(buffer, size));
                EventBus.getDefault().post(new EventT(EventT.EventType.BaseCallCode, buffer));
            }
        };

        printUtil = new ChuanKouUtils(new DevicesInfo("ttyS1", "/dev/ttyS1"), 9600) {
            @Override
            protected void onDataReceived(byte[] buffer, int size) {
                Log.i("ChuanKouInfo", "收到串口信息：" + ChuanKouUtils.showByte(buffer, size));
                EventBus.getDefault().post(new EventT(EventT.EventType.Print, buffer));
            }
        };

        audioUtil = new AudioDao(getApplicationContext());

        String newTime = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE).format(new Date());
        String oldTime = SPUtil.getObject(V.SP_UP_START_TIME);
        if (!newTime.equals(oldTime)) {
            SPUtil.saveObject(V.SP_UP_START_TIME, newTime);
            daoSession.getBusinessDao().deleteAll();
        }
    }

    private void initGreenDao() {
        // 通过DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为greenDAO 已经帮你做了。
        // 注意：默认的DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

}
